import 'package:get/get.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/application/day_info_list_entity.dart';
import 'package:safetymonitor/app/data/entities/home/duty/month_duty_date_entity.dart';
import 'package:safetymonitor/modules/home/home_page/duty_manager/duty/view.dart';
import 'package:table_calendar/table_calendar.dart';

class DutyMgmtPageController extends GetxController {
  CalendarFormat calendarFormat = CalendarFormat.week;
  bool curry = false;

  /// 事件列表
  List<EventModel> eventsList = [];

  // DateTime selectedDate = DateTime.now();
  Rx<DateTime> selectedDate = DateTime.now().obs;

  /// 一个月的排班信息
  List<DayInfoListEntity> listDayInfoListEntity = [];

  @override
  void onInit() {
    super.onInit();
    getDayInfoList();
    getMonthEvent().then((monthEvent) {
      eventsList = monthEvent;
      for (var i = 0; i < monthEvent.length; i++) {
        if (isSameDay(monthEvent[i].date, DateTime.now())) {
          curry = true;
        } else {
          curry = false;
        }
      }
      // 定位到该月第一个事件
      // if (eventsList.isNotEmpty) {
      //   _selectedDate.value = eventsList.first.date;
      // }
    });
  }
  bool isNotPermissions=true;
  /// 获取一个月的排班信息
  void getDayInfoList({bool isUpDate = false}) async {
    final resp = await HttpUtil().generateGetRequest<List<DayInfoListEntity>>(
      Interface.dayInfoList,
      queryParameters: {
        'queryMonth':
            '${selectedDate.value.year}-${selectedDate.value.month.toString().padLeft(2, '0')}',
        'companyId': UserManager.getUserCompanyId(),
      },
    ).execute();
    if (resp.isSucceed && resp.data != null) {
      listDayInfoListEntity = resp.data ?? [];
      selectDayPB(selectedDate.value,isUpDate: isUpDate);
      isNotPermissions=true;
    }
    resp.onError((result) {
      if(result.code==403&&result.message=='没有该操作权限'){
        isNotPermissions=false;
        update();
      }
    });
  }

  Future<List<EventModel>> getMonthEvent() async {
    final List<EventModel> events = [];

    /// 获得1个月的事件
    final resp = await HttpUtil().generateGetRequest<List<MonthDutyDateEntity>>(
      Interface.dayInfoListEvent,
      queryParameters: {
        'queryMonth':
            '${selectedDate.value.year}-${selectedDate.value.month.toString().padLeft(2, '0')}',
        'companyId': UserManager.getUserCompanyId(),
      },
    ).execute();
    if (resp.isSucceed && resp.data != null) {
      final List<MonthDutyDateEntity> list = resp.data!;
      for (int i = 0; i < list.length; i++) {
        if (list[i].dutyPersons.isEmpty && list[i].dutyLeaders.isEmpty) {
          continue;
        }
        final split = list[i].dutyDate.split('-');
        if (split.length == 3) {
          events.add(EventModel(
              title: list[i].count,
              date: DateTime(int.parse(split[0]), int.parse(split[1]),
                  int.parse(split[2]))));
        }
      }
    }
    return events;
  }

  DayInfoListEntity selsectOneDaylist = DayInfoListEntity();

  /// 选中一天 显示排班信息
  void selectDayPB(DateTime month, {bool isUpDate = false}) {
    if (listDayInfoListEntity.isNotEmpty) {
      selsectOneDaylist = listDayInfoListEntity
          .where(
            (e) =>
                '${month.year}-${month.month.toString().padLeft(2, '0')}-${month.day.toString().padLeft(2, '0')}'
                    .contains(e.dutyDate ?? ''),
          )
          .toList()[0];
    }
    if(isUpDate){
      update();
    }else{
      update(['_buildBody']);
    }
  }

  /// 我们创建了一个新的 DateTime 实例 today，它只包含了当前的年、月、日信息，忽略了时间部分。
  /// 使用 isAfter 方法检查 inputDate 是否在 today 之后。
  /// 使用 isAtSameMomentAs 方法检查 inputDate 是否正好等于 today。
  /// 这样，如果输入的日期是今天或者未来的任意一天，函数都会返回 true。
  bool isFutureOrTodayDate(DateTime dateString) {
    // final inputFormat = DateFormat("yyyy-MM-dd");
    // final inputDate = inputFormat.parse(dateString);
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day); // 只保留日期部分
    return dateString.isAfter(today) || dateString.isAtSameMomentAs(today);
  }
}
